package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.CarSupplierOrderDto;
import com.ant.storage.dto.SupplierOrderDto;
import com.ant.storage.dto.SupplierPayListDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.CarSupplierPayMapper;
import com.ant.storage.mapper.PurchaserRecordMapper;
import com.ant.storage.mapper.SubscribeMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.utils.DateFormat;
import com.ant.storage.utils.RandomUtil;
import com.ant.storage.vo.SingleVo;
import com.ant.storage.vo.SupplierPayListVo;
import com.ant.storage.wechat.WeChatUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.api.ApiException;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2024-01-03
 */
@Service
public class CarSupplierPayServiceImpl extends ServiceImpl<CarSupplierPayMapper, CarSupplierPay> implements ICarSupplierPayService {

    @Autowired
    public ServletContext servletContext;

    @Autowired
    public ICarSupplierPayService payService;

    @Resource
    private IPurchaserRecordImgService imgService;

    @Resource
    private PurchaserRecordMapper recordMapper;

    @Resource
    private SubscribeMapper subscribeMapper;

    @Autowired
    private IPurchaserRecordService recordService;

    @Resource
    private IRecordOrderService recordOrderService;

    @Autowired
    public IApprovalMsgService approvalMsgService;

    @Override
    public PageInfo<CarSupplierPay> querylist(SupplierPayListDto dto) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (userInfo == null) {
            throw new AntException(ResultCode.FAILURE.getCode(), "登录超时");
        }
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        QueryWrapper<CarSupplierPay> wrapper = new QueryWrapper<>();

        if (dto.getSupplierId() != null) {
            wrapper.eq("supplier_id", dto.getSupplierId());
        }
        if (dto.getStatus() != null) {
            wrapper.eq("status", dto.getStatus());
        }
        if (dto.getTime() != null && dto.getTime().size() != 0) {
            wrapper.ge("delivery_time", dto.getTime().get(0) + " 00:00:00");
            wrapper.le("delivery_time", dto.getTime().get(1) + " 23:59:59");
        }
        wrapper.eq("is_delete", 1);
        wrapper.orderByDesc("id");
        List<CarSupplierPay> pickingList = this.baseMapper.selectList(wrapper);
        PageInfo<CarSupplierPay> pageInfo = new PageInfo<>(pickingList);
        return pageInfo;
    }

    @Resource
    IAuditListService auditListService;

    /**
     * 通过id查询供应商采购新
     *
     * @return
     */
    @Override
    public PageInfo<SupplierPayListVo> findPaymenList(SupplierOrderDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        List<SupplierPayListVo> supplierPayListVos = this.baseMapper.findSupplierPaymenById(dto);
        PageInfo<SupplierPayListVo> info = new PageInfo<>(supplierPayListVos);
        return info;
    }

    @Override
    public ResultVo SupplierSettlementSave(CarSupplierOrderDto dto) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (dto.getIds().length == 0) {
            throw new AntException(ResultCode.FAILURE.getCode(), "数据不能为空!!!");
        }
        ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(dto.getIds()));
        arrayList.stream().forEach(item -> {
            UpdateWrapper<CarSupplierPay> wrapper = new UpdateWrapper<>();
            wrapper.set("pay_status", 1);
            wrapper.set("handle_id", 1);
            wrapper.set("handle_time", new Date());
            wrapper.eq("supplier_id", dto.getSupplierId());
            wrapper.eq("subscribe_id", item);
            payService.update(wrapper);
        });
        PurchaserRecord purchaserRecord = new PurchaserRecord();
        purchaserRecord.setRecordNumber("RCD" + RandomUtil.getOrderNumbers(recordMapper.selectLastID()));
        purchaserRecord.setCreationTime(new Date());
        purchaserRecord.setCityId(userInfo.getCityId());
        purchaserRecord.setPurchaserId(userInfo.getNameId());
        purchaserRecord.setReimbursementAmount(new BigDecimal(dto.getConsumePrice()));
        purchaserRecord.setImgUrlId(dto.getAnnex());
        purchaserRecord.setRemarks(dto.getRemarks());
        purchaserRecord.setTypes(4);//汽车报销
        purchaserRecord.setSupplierId(Integer.parseInt(dto.getSupplierId()));
        recordService.save(purchaserRecord);
        List<SingleVo> singleVos = singleVos(Integer.parseInt(dto.getSupplierId()), dto.getIds());
        List<RecordOrder> recordOrders = singleVos.stream().map(item -> {
            RecordOrder orders = new RecordOrder();
            orders.setPurchaserRecordId(purchaserRecord.getId());
            orders.setPurchaseOrdersId(item.getId());
            return orders;
        }).collect(Collectors.toList());
        recordOrderService.saveBatch(recordOrders);
        if (dto.getIsApproved() == 1) {
            // 添加审核
            AuditList auditList = new AuditList();
            auditList.setParentId(purchaserRecord.getId());
            auditList.setProcessType("reimbursement");
            auditList.setCreationTime(new Date());
            // 添加审核记录
            for (String str : dto.getApproval()) {
                auditList.setNameId(str);
                auditList.setTypes("1");
                auditListService.save(auditList);
            }
            for (String str2 : dto.getNotify()) {
                auditList.setNameId(str2);
                auditList.setTypes("2");
                auditListService.save(auditList);
            }
            String str = addWeChatData(dto);
            ApprovalMsg msg=new ApprovalMsg();
            msg.setParentId(purchaserRecord.getId());
            msg.setApprovalType("reimbursement");
            msg.setApprovalUser(userInfo.getUserName());
            msg.setApprovalUserId(userInfo.getNameId());
            msg.setSpNo(str);
            msg.setCreationTime(new Date());
            approvalMsgService.save(msg);
            UpdateWrapper<PurchaserRecord> updateWrapper = new
                    UpdateWrapper<PurchaserRecord>().set(
                    "process_instance_id", str).eq("id", purchaserRecord.getId());
            recordService.update(updateWrapper);
            return ResultVo.success("操作成功");

//            try {
//                FundsDto fundsDto = new FundsDto();
//                fundsDto.setAccess_token(DingDingUtil.obtainToken());
//                fundsDto.setOriginator_userid(userInfo.getDingTalk());
//                fundsDto.setDeptId(userInfo.getDepId());
//                fundsDto.setApprover_userid(dto.getApproval());
//                fundsDto.setCc_userId(dto.getNotify());
//                fundsDto.setDate(DateFormat.getCurrentDates());
//                fundsDto.setUrgency(dto.getUrgency() == "" ? "24小时完成" : dto.getUrgency());
//                fundsDto.setAmount(dto.getConsumePrice().toString());
//                fundsDto.setPicture(getPicture(dto.getAnnex()));
//                fundsDto.setReason(dto.getRemarks());
//                fundsDto.setCompanyName(userInfo.getDepName());
//                if (singleVos != null) {
//                    List<ReimbursementProjectDto> collect = singleVos.stream().map(m -> {
//                        ReimbursementProjectDto dto1 = new ReimbursementProjectDto();
//                        dto1.setProjectName(m.getCommodityName());
//                        dto1.setAmount(m.getCommodityNumber().toString());
//                        dto1.setProjectPrice(m.getCommodityPrice());
//                        dto1.setTotalPrice(m.getCommodityNumber().multiply(m.getCommodityPrice()));
//                        return dto1;
//                    }).collect(Collectors.toList());
//                    fundsDto.setProjectDtoList(collect);
//                } else {
//                    fundsDto.setProjectDtoList(null);
//                }
//                //  return ResultVo.success("操作成功");
//                String process_instance_id = DingDingUtil.Reimbursement(fundsDto);
//                if (process_instance_id.equals("201")) {
//                    return ResultVo.fail("操作失败");
//                } else {
//                    UpdateWrapper<PurchaserRecord> updateWrapper = new
//                            UpdateWrapper<PurchaserRecord>().set(
//                            "process_instance_id", process_instance_id).eq("id", purchaserRecord.getId());
//                    recordService.update(updateWrapper);
//                    return ResultVo.success("操作成功");
//                }
//            } catch (Exception e) {
//                return ResultVo.fail("操作失败");
//            }
        }
        return ResultVo.success("操作成功");
    }

    public List<String> getPicture(String str) throws ApiException {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        List<Integer> list = Arrays.asList(str.split(",")).
                stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        List<PurchaserRecordImg> imgList = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                .in("id", list));
        List<String> collect = new ArrayList<>();
        if (imgList.size() <= 5) {
            imgList.stream().forEach(item -> {
                collect.add(item.getUrl());
            });
        } else {
            imgList.subList(0, 5).stream().forEach(item -> {
                collect.add(item.getUrl());
            });
        }
        //   List<String> collect = imgList.stream().map(p -> p.getUrl()).collect(Collectors.toList());
        return collect;
    }


    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public String addWeChatData(CarSupplierOrderDto dto) throws AntException {
        InvoiceInfo info = new InvoiceInfo();
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        info.setWeChat(userInfo.getWeChat());
        info.setUserName(userInfo.getUserName());
        info.setInvoiceName(dto.getInvoiceName());
        info.setReimbursementTypeText("汽修类物质保险");
        info.setApproval(dto.getApproval());
        info.setNotify(dto.getNotify());
        info.setAccountUrgency(dto.getUrgency());
        info.setInvoicePrice(new BigDecimal(dto.getConsumePrice()));
        info.setStartTime(DateFormat.simpleDateFormats(dto.getDate()));
        info.setEndTime(DateFormat.simpleDateFormats(dto.getDate()));
        info.setInvoiceNotes(dto.getRemarks());
        info.setAccountName(dto.getRemarks());
        info.setAccountNumber(dto.getAccountNumber());
        info.setAccountBank(dto.getAccountBank());
        //物品列表
        List<SingleVo> singleVos = singleVos(Integer.parseInt(dto.getSupplierId()), dto.getIds());
        List<ReimburseDetail> list = new ArrayList<>();
        if (singleVos != null && singleVos.size() > 0) {
            singleVos.forEach(item -> {
                ReimburseDetail detail = new ReimburseDetail();
                detail.setProjectName(item.getCommodityName());
                detail.setProjectAmount(item.getCommodityNumber().toString());
                detail.setProjectUnit(item.getCommodityUnits());
                detail.setProjectPrice(item.getCommodityPrice());
                list.add(detail);
            });
        }
        info.setDetailList(list);
        String str = WeChatUtils.launchWeChatData(info);



        return str;
    }

    public List<SingleVo> singleVos(Integer supplierId, Integer[] ids) {
        if(ids.length==0){
            throw  new AntException(ResultCode.FAILURE.getCode(),"id不能为空");
        }
        ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(ids));
        List<SingleVo> singleVos = subscribeMapper.selectBatchByIds(supplierId, arrayList);
        if (singleVos != null && singleVos.size() > 0) {
            return singleVos;
        } else {
            return null;
        }
    }


}
